(ns clj-gallery.routes.gallery
  (:require [compojure.core :refer :all]
            [hiccup.page :refer [include-js]]
            [hiccup.element :refer :all]
            [hiccup.form :refer [check-box]]

            [clj-gallery.views.layout :as layout]
            [clj-gallery.util :refer [login-user-id thumb-prefix image-uri thumb-uri]]
            [clj-gallery.models.db :as db]))

(defn thumbnail-link [{:keys [userid name]}]
  [:div.thumbnail
   [:a {:class name
        :href  (image-uri userid name)}
    [:span name]
    [:br]
    (image (thumb-uri userid name))
    (when (= userid (login-user-id))
      (check-box name))]])

#_(defn display-gallery [userid]
    (if-let [gallery (not-empty (map thumbnail-link (db/images-by-user userid)))]
      [:div
       [:div#error]
       gallery
       (when (= userid (login-user-id))
         [:input#delete {:type "submit" :value "delete images"}])]
      [:p "The user " userid " does not have any galleries"]))

(defn gallery-link [{:keys [userid name]}]
  [:div.thumbnail
   [:a {:href (str "/gallery/" userid)}
    (image (thumb-uri userid name))
    userid "'s gallery"]])

(defn show-galleries []
  (map gallery-link (db/get-gallery-previews)))

(defn display-gallery [userid]
  (layout/render "gallery.html" {:thumb-prefix thumb-prefix
                                 :page-owner   userid
                                 :pictures     (db/images-by-user userid)}))

(defroutes gallery-routes
  (GET "/gallery/:userid" [userid] (display-gallery userid)))